package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchant.pojo.Sku;
import cc.linker.steplink.crm.merchanth5.dao.coupon.CouponH5Dao;
import cc.linker.steplink.crm.response.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsLossGoodsService {

    @Autowired
    private CouponH5Dao couponH5Dao;
    @Autowired
    private CouponRequest couponRequest;

    /**
     * 根据商品id，查询所有的优惠券
     */
    public  List<Map<String, Object>> getCouponListByGoodsId(PcUserInfo userInfo, Long goodsId){
        CouponCustomerInfo customerInfo = CouponCustomerInfo
                .builder()
                .customerId(userInfo.getSaler() ? userInfo.getCustomerId() : userInfo.getOrgId())
                .customerName(userInfo.getAdminName())
                .customerPhone("15012345678")
                .cover("")
                .orgId(userInfo.getOrgId())
                .build();
        String orgId = "";
        String belongId = "";
        if(userInfo.getSaler()){
            String adminId = userInfo.getAdminId();
            belongId = couponH5Dao.getCustomerIdByUserId(adminId);
        }else {
            orgId =  userInfo.getOrgId();
        }
        //查询符合该商品的优惠券
        Map<String, Object> param = new HashMap<>();
        List<String> couponIds= couponH5Dao.getCouponIdByGoodsId(goodsId,belongId,orgId);
        List<Map<String, Object>> dataList=null;
        if(couponIds!=null && couponIds.size()>0){
            param.put("couponIds",String.join(",",couponIds));
//            param.put("notEnd",1);
            Object list = couponRequest.doRequest("coupon-all-list", param, customerInfo);
            dataList = (List<Map<String, Object>>) list;
        }
        if(dataList==null){
            dataList = new ArrayList<>();

        }
        return dataList;
    }


    /**
     * 根据商品id，查询所有的优惠券
     */
    public  List<Map<String, Object>> getCouponListByGoodsIdTemplate(PcUserInfo userInfo, Long goodsId){
        CouponCustomerInfo customerInfo = CouponCustomerInfo
                .builder()
                .customerId(userInfo.getSaler() ? userInfo.getCustomerId() : userInfo.getOrgId())
                .customerName(userInfo.getAdminName())
                .customerPhone("15012345678")
                .cover("")
                .orgId(userInfo.getOrgId())
                .build();
        //查询符合该商品的优惠券
        Map<String, Object> param = new HashMap<>();
        List<String> couponIds= couponH5Dao.getCouponIdByGoodsId(goodsId,"","");
        List<Map<String, Object>> dataList=null;
        if(couponIds!=null && couponIds.size()>0){
            param.put("couponIds",String.join(",",couponIds));
//            param.put("notEnd",1);
            Object list = couponRequest.doRequest("coupon-all-list", param, customerInfo);
            dataList = (List<Map<String, Object>>) list;
        }
        if(dataList==null){
            dataList = new ArrayList<>();

        }
        return dataList;
    }


    /**
     * @Description: 折扣后商品价格
     * @Param: [goodsInfo 商品详情, couponInfo 优惠券详情]
     * @Return: java.util.Map
     * @Author: ch
     * @Date: 2020/8/29 13:20
     * @Version:
     **/
    public Map reduceGoodsInfoByMap(Map goodsInfo,Map couponInfo){
        //消费券类型
        Integer type = (Integer) couponInfo.get("type");
        Object sku = goodsInfo.get("sku");
        List<Sku> newSku = (List<Sku>) sku;
        if(type==0){
            //满减
            //满减金额
            Integer minUsePrice = 0;
            Integer discountPrice =0;
            if(!StringUtils.isEmpty(couponInfo.get("minUsePrice"))){
                Double minUsePriceD = Double.valueOf(couponInfo.get("minUsePrice").toString());
                minUsePrice = minUsePriceD.intValue();
            }
            if(!StringUtils.isEmpty(couponInfo.get("discountPrice"))){
                Double discountPriced = Double.valueOf(couponInfo.get("discountPrice").toString());
                discountPrice = discountPriced.intValue();
            }
            if(newSku==null || newSku.size()<1){
                // 单规格
                // 销售金额
                double amount = Double.parseDouble(goodsInfo.get("moneyAmount").toString())*100;
                if(amount<minUsePrice){
                    goodsInfo.put("isFreeFreight",1);
                }
                amount = this.reduceAmount(amount,minUsePrice,discountPrice);
//                goodsInfo.put("moneyAmount",amount/100);
                goodsInfo.put("reduceAmount",amount/100);
                // 会员价来判断是否亏损
                if(!StringUtils.isEmpty(goodsInfo.get("memberAmount")) && !"0".equals(goodsInfo.get("memberAmount").toString())){
                    // 会员价
                    double memberAmount = Double.parseDouble(goodsInfo.get("memberAmount").toString())*100;
                    if(memberAmount>0){
                        if(memberAmount<minUsePrice){
                            goodsInfo.put("isFreeFreight",1);
                        }
                        memberAmount = this.reduceAmount(memberAmount,minUsePrice,discountPrice);
//                    goodsInfo.put("memberAmount",memberAmount/100);
                        goodsInfo.put("reduceMemberAmount",memberAmount/100);
                    }
                }
            }else {
                // 多规格
                for(int i=0;i<newSku.size();i++){
                    Object o2 = newSku.get(i);
                    Map o = BeanMapUtils.beanToMap(o2);
                    if(o.containsKey("empty")){
                        o = (Map<String,Object>)o2;
                    }
                    try {
//                        Sku o = BeanMapUtils.mapToBean(o1,Sku.class);
//                        Map<String,Object> o = o1;
                        // 销售金额
                        double amount = 0;
                        if(!StringUtils.isEmpty(o.get("moneyAmount"))) {
                            amount = Double.valueOf(o.get("moneyAmount").toString()) * 100;
                        }
                        if(amount<minUsePrice){
                            goodsInfo.put("isFreeFreight",1);
                        }
                        amount = this.reduceAmount(amount,minUsePrice,discountPrice);
                        newSku.get(i).setReduceAmount(amount/100);
//                        o.put("reduceAmount",amount/100);
                        // 会员价来判断是否亏损
                        if(!StringUtils.isEmpty(o.get("memberAmount"))){
                            // 会员价
                            double memberAmount = Double.valueOf(o.get("memberAmount").toString())*100;
                            if(memberAmount>0){
                                if(memberAmount<minUsePrice){
                                    goodsInfo.put("isFreeFreight",1);
                                }
                                memberAmount = this.reduceAmount(memberAmount,minUsePrice,discountPrice);
                                newSku.get(i).setReduceMemberAmount(memberAmount/100);
//                                o.put("reduceMemberAmount",memberAmount/100);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }else if(type==1){
            //折扣
            Integer maxDiscountPrice = 0;
            Integer discountNum = 0;
            if(!StringUtils.isEmpty(couponInfo.get("maxDiscountPrice"))){
                Double maxDiscountPriceD = Double.valueOf(couponInfo.get("maxDiscountPrice").toString());
                maxDiscountPrice = maxDiscountPriceD.intValue();
            }
            if(!StringUtils.isEmpty(couponInfo.get("discountNum"))){
                Double discountNumD = Double.valueOf(couponInfo.get("discountNum").toString());
                discountNum = discountNumD.intValue();
            }
            Integer minUsePrice = 0;
            if(!StringUtils.isEmpty(couponInfo.get("minUsePrice"))){
                Double minUsePriceD = Double.valueOf(couponInfo.get("minUsePrice").toString());
                minUsePrice = minUsePriceD.intValue();
            }
            if(newSku==null || newSku.size()<1){
                // 单规格
                // 销售金额
                double amount = Double.parseDouble(goodsInfo.get("moneyAmount").toString())*100;
                if(amount<minUsePrice){
                    goodsInfo.put("isFreeFreight",1);
                }
                amount = this.reduceAmountD(amount,maxDiscountPrice,discountNum);
                goodsInfo.put("reduceAmount",amount/100);
//                goodsInfo.put("moneyAmount",amount/100);
                // 会员价来判断是否亏损
                if(!StringUtils.isEmpty(goodsInfo.get("memberAmount")) && !"0".equals(goodsInfo.get("memberAmount").toString())){
                    // 会员价
                    double memberAmount = Double.parseDouble(goodsInfo.get("memberAmount").toString())*100;
                    if(memberAmount>0){
                        if(memberAmount<minUsePrice){
                            goodsInfo.put("isFreeFreight",1);
                        }
                        memberAmount = this.reduceAmountD(memberAmount,maxDiscountPrice,discountNum);
//                    goodsInfo.put("memberAmount",memberAmount/100);
                        goodsInfo.put("reduceMemberAmount",memberAmount/100);
                    }
                }
            }else {
                // 多规格
                for(int i=0;i<newSku.size();i++){
                    Object o2 = newSku.get(i);
                    Map o = BeanMapUtils.beanToMap(o2);
                    if(o.containsKey("empty")){
                        o = (Map<String,Object>)o2;
                    }
                    try {
//                        Sku o = BeanMapUtils.mapToBean(o1,Sku.class);
//                        Map<String,Object> o = o1;
                        // 销售金额
                        double amount = 0;
                        if(!StringUtils.isEmpty(o.get("moneyAmount"))) {
                            amount = Double.valueOf(o.get("moneyAmount").toString()) * 100;
                        }
                        if(amount<minUsePrice){
                            goodsInfo.put("isFreeFreight",1);
                        }
                        amount = this.reduceAmountD(amount,maxDiscountPrice,discountNum);
                        newSku.get(i).setReduceAmount(amount/100);
//                        o.put("reduceAmount",amount/100);
                        // 会员价来判断是否亏损
                        if(!StringUtils.isEmpty(o.get("memberAmount"))){
                            // 会员价
                            double memberAmount = Double.valueOf(o.get("memberAmount").toString())*100;
                            if(memberAmount>0){
                                if(memberAmount<minUsePrice){
                                    goodsInfo.put("isFreeFreight",1);
                                }
                                memberAmount = this.reduceAmountD(memberAmount,maxDiscountPrice,discountNum);
//                                o.put("reduceMemberAmount",memberAmount/100);
                                newSku.get(i).setReduceMemberAmount(memberAmount/100);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsInfo.get("goodsId"));
                        throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                    }
                }
            }
        }
        return goodsInfo;
    }


    /**
     * @Description: 满减后金额
     * @Param: [amount 价格, minUsePrice 满减金额，discountPrice 优惠金额]
     * @Return: java.util.Map
     * @Author: ch
     * @Date: 2020/8/29 13:20
     * @Version:
     **/
    public double reduceAmount(double amount,Integer minUsePrice,Integer discountPrice){
        //比例后的折扣金额（价格小于满减金额）
        Integer resDiscountPrice = discountPrice;
        if(amount>=minUsePrice && amount>discountPrice){
            //价格大于满减金额，并且大于优惠金额
            amount = amount-discountPrice;
        }else if(amount>=minUsePrice && amount<=discountPrice){
            //价格大于满减金额，并且小于优惠金额
            amount = 0;
        }else if(amount<minUsePrice){
            //价格小于满减金额
            resDiscountPrice = new BigDecimal(discountPrice*amount/minUsePrice).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            if(resDiscountPrice==0 && discountPrice>=amount){
                //进位后为0，优惠金额大于价格
                amount = 0;
            }else if(resDiscountPrice==0 && discountPrice<amount){
                //进位大于0，优惠金额小于价格
                amount = amount - discountPrice;
            }else if(resDiscountPrice>0 && resDiscountPrice>=amount){
                //进位大于0，优惠金额大于价格
                amount = 0;
            }else if(resDiscountPrice>0 && resDiscountPrice<amount) {
                amount = amount - resDiscountPrice;
            }
        }
        return amount;
    }

    /**
     * @Description: 折扣后金额
     * @Param: [amount 价格, maxDiscountPrice 最大优惠金额，discountNum 折扣数]
     * @Return: java.util.Map
     * @Author: ch
     * @Date: 2020/8/29 13:20
     * @Version:
     **/
    public double reduceAmountD(double amount,Integer maxDiscountPrice,Integer discountNum){
        //折扣金额
//        int discountPrice = new BigDecimal(amount*discountNum/1000).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
        int discountPrice = new BigDecimal(amount - (amount*discountNum/1000)).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
        discountPrice =  (int) (amount- discountPrice);
        if(discountPrice>maxDiscountPrice && maxDiscountPrice>0){
            //折扣金额大于最大优惠金额
            amount = amount-maxDiscountPrice;
        }else if(maxDiscountPrice==null || maxDiscountPrice==0){
            amount = discountPrice;
        }else if(discountPrice<maxDiscountPrice && discountPrice>0){
            //折扣金额小于最大优惠金额，且折扣金额大于0
            amount = discountPrice;
        }
        return amount;
    }
}
